import React, { Component, PropTypes } from 'react';
import {
  Text,
  View,
  ScrollView,
  TouchableOpacity,
  Image,
  Dimensions,
  Platform,
  ListView,
  InteractionManager
} from 'react-native';

import ScrollableTabView from 'react-native-scrollable-tab-view';
import ScrollableTabBar from '../global/scrollableTabView/ScrollableTabBar';
import Button from '../global/scrollableTabView/Button';
import _ from 'lodash';

import styles from './orderListStyle';
import CustomListView from '../global/CustomListView';
import ListViewActivityIndicator from '../global/ListViewActivityIndicator';

import OrderCard from './orderCard';
import api from '../../services/api';
import ToastTip from '../global/ToastTip';
import LoadingTip from '../global/LoadingTip';
import Touch from '../global/Touch';
import DeviceStorage from '../global/DeviceStorage';
// import { Navigation } from '../global/navigation/index';
import {Loading, EasyLoading} from '../global/EasyLoading';

const {width: deviceWidth, height: deviceHeight} = Dimensions.get('window');

class OrderList extends Component {
    constructor(props) {
		super(props);

		this.state = {
			currentPage: 1,
            noData: false,
            pagesize: 10,
            showLoading: false,
            overThreeTimeStyle: null,
            allStyle: {color: '#EA5404'},
            searchTab: -1,
		};

		this._onRefresh = this._onRefresh.bind(this);
		this._onLoadMore = this._onLoadMore.bind(this);
		this._viewOrder = this._viewOrder.bind(this);
        this.list = [];
        this.totalpage = 0;
        this.serviceTypeMap = ['send', 'buy', 'express', 'lockkey', 'other','nursing'];
        this.curTab = 0;
        this.overThreeTimeStyle = null;
        this.searchStr = '';
        this.currentPage = 1;

		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    componentDidMount() {
        this.onLoad();
	}

    // _onNavigatorEvent(event){
    //     // console.log("$$$", event);
    //
    //     if (event.type === 'ScreenChangedEvent') {
	// 		if (event.id === 'didAppear') { //出现时
    //             this.onLoad();
	// 		}
	// 	}
    // }

    onLoad(data, searchStr){
        //加载数据
        if(this.state.noData){
            this.setState({ noData: false});
        }

        this.cur_type = data;
        this.searchStr = searchStr;
        this.loadingCont = this.refs.loading;

        // this.setState({ showLoading: true,});
        // Navigation.loadingTips({action:'show', tip:'加载中...'});
        // EasyLoading.show('加载中...', -1);
        this.loadingCont.setState({ "isShow": true, "text": '加载中...' });

        this._orderList._pullToRefreshListView._scrollView.scrollTo({y:0});
        //清空数据
        this._orderList && this._orderList.setState({
            dataList: [],
            dataSource: this._orderList._dataSource.cloneWithRows([])
        });

        this._orderList._pullToRefreshListView.beginRefresh(true);
    }

    async _retrieveOrderList() {
        let list;
        let status = this.props.status==0?1:this.props.status;
        let user_role = this.props.session.user.role;
        console.log('test------_retrieveOrderList=status',status);
        list = await api.post('/order/list', {
                      status: status,
                      page: 1,
                      pagesize: this.state.pagesize,
                      //serviceType: this.curTab==999?'':(user_role==1?this.serviceTypeMap[this.curTab]:''),
                      searchTerm: this.searchStr,
                      isOvertime: this.props.status==0&&this.overThreeTimeStyle?'1':'',
                      isThirdParty: this.props.status!=0&&this.overThreeTimeStyle?'1':''
                   });
        console.log('test------_retrieveOrderList',list);
        if(list.cd == 1){
            // this.setState({ showLoading: false,});
            // Navigation.loadingTips({action:'hide'});
            // EasyLoading.dismis();
            this.loadingCont.setState({ "isShow": false });
            this.refs.toast.show(list.msg);
            this._orderList._pullToRefreshListView.endRefresh(false);
            return;
        }

       // not pay
       setTimeout(() => {
           this._endOrderList(list.data);
       }, Platform.OS == 'ios'?100:300);

    }

    async _endOrderList(list){
        this.totalpage = list.total_page;
        this.list = list.res;

        let {actions, dispatch} = this.props;
        let user_role = this.props.session.user.role;

        // dispatch(actions.order.order_done_obj_price(''));
console.log('test--------------666',this.list.length);
        if(this.list.length==0){
            // Navigation.loadingTips({action:'hide'});
            // EasyLoading.dismis();
            this.loadingCont.setState({ "isShow": false });

            this.setState({noData: true});
//<<<<<<< HEAD
            //this.props.parent.updateMarkNum(this.props.tab, 0);
//=======
            this.setState({ showLoading: false,});
            // this._orderList._pullToRefreshListView.endRefresh(false);
//>>>>>>> master-temp

            this._orderList && this._orderList.setState({
                dataList: [{isnodate: true}],
                dataSource: this._orderList._dataSource.cloneWithRows([{isnodate: true}])
            });
//<<<<<<< HEAD
            this._orderList && this._orderList._pullToRefreshListView.endRefresh(false);

            //重新获取角标
            this.props.parent._getOrderCount();
//=======
            this.props.parent.updateMarkNum(this.props.tab, 0);
//>>>>>>> master-temp
            return;
        }

        // this.setState({ currentPage: 1 });
        this.currentPage = 1;

        this._orderList && this._orderList.setState({
            dataList: list.res,
            dataSource: this._orderList._dataSource.cloneWithRows(list.res)
        });

        // if(this.props.tab == 0){
        //     // let no_pay_list = _.filter(list.res, function(o) { return o.status == 1 || o.service_type == 'express' || o.service_type=='lockkey'; });
        //     this.props.parent.updateMarkNum(0, this.total_count);
        // }else {
        //     this.props.parent.updateMarkNum(this.props.tab, this.total_count);
        // }

console.log('test--------------ttt',this.list.length);
        // this._activityIndicator.setState({ visible: false,});

//<<<<<<< HEAD
        this._orderList && this._orderList._pullToRefreshListView.endRefresh(false);

        // Navigation.loadingTips({action:'hide'});
        // EasyLoading.dismis();
        this.loadingCont.setState({ "isShow": false });

        //重新获取角标
        await this.props.parent._getOrderCount();

        // this.setState({ showLoading: false,});
        // if(this.props.tab == 2 && (this.curTab == 1 || user_role != 1)){//初始化代买未支付商品金额
            // let tempIds = [];
            // for (var i = 0; i < this.list.length; i++) {
            //     if(this.list[i].obj_pay_status == 1){//未支付
            //         tempIds.push(this.list[i].id);
            //     }
            // }
            // dispatch(actions.order.order_done_obj_price(tempIds));
        // }

        //setTimeout(()=>{
//=======
        //
        setTimeout(() =>{
//>>>>>>> master-temp
            this.cur_type && DeviceStorage.delete("@order@"+this.cur_type);
            this.cur_type = null;
        }, 100);
    }

    async _retrieveNextPage(status) {
		if (this.currentPage < this.totalpage) {
            let {actions, dispatch} = this.props;

			let page;
            page = this.currentPage + 1;
            this.currentPage = page;

           let list;
           // if(this.props.status == 0){
           //     list = await api.post('/order/createlist', {
           //                   page: page,
           //                   pagesize: this.state.pagesize
           //                });
           // }else {
           //     list = await api.post('/order/list', {
           //                   status: status,
           //                   page: page,
           //                   pagesize: this.state.pagesize
           //                });
           // }
           let user_role = this.props.session.user.role;

           let status = this.props.status==0?1:this.props.status;

           list = await api.post('/order/list', {
                         status: status,
                         page: page,
                         pagesize: this.state.pagesize,
                         //serviceType: this.curTab==999?'':(user_role==1?this.serviceTypeMap[this.curTab]:''),
                         searchTerm: this.searchStr,
                         isOvertime: this.props.status==0&&this.overThreeTimeStyle?'1':'',
                         isThirdParty: this.props.status!=0&&this.overThreeTimeStyle?'1':''
                      });

           if(list.cd == 1){
               this.refs.toast.show(list.msg);
               this._orderList._pullToRefreshListView.endLoadMore(true);
               return;
           }
        //    const data = this.list;
           const newData = list.data.res;
           newData.map((item, index) => {
               this.list.push(item);

           });
//<<<<<<< HEAD
//=======
           let tempIds=[];
           this.list.map((item) =>{
            //    console.warn(item);
               if(this.props.tab == 2 && (item.obj_pay_status == 5||item.servicePayStatus==1)){
                   tempIds.push(item.id);
               }
           });
//>>>>>>> master-temp

           if(this.props.tab == 2 && (this.curTab == 1 || user_role != 1)){
               // let tempIds=[];
               // this.list.map((item)=>{
               //     if(this.props.tab == 2 && item.obj_pay_status == 1){
               //         tempIds.push(item.id);
               //     }
               // });
               // dispatch(actions.order.order_done_obj_price(tempIds));
           }

           this._orderList.setState({
               dataList: this.list,
               dataSource: this._orderList._dataSource.cloneWithRows(this.list),
           });
           this._orderList._pullToRefreshListView.endLoadMore(false);

        }else{
            this._orderList._pullToRefreshListView.endLoadMore(true);
        }
	}

    _viewOrder(orderId,cardObj) {
        let {navigator} = this.props;
        // dispatch(actions.order.order_get_cardobj(cardObj));
		navigator.push({
            title: "订单详情",
            backButtonTitle:'',
			screen: 'housekeeperapp.orderdetail',
			passProps: {
				orderId
			},
            navigatorStyle:{
                tabBarHidden: true,
                navBarTextColor: 'white',
            	navBarButtonColor: 'white',
            	navBarBackgroundColor: '#EA5404',
                statusBarColor: '#EA5404',
                navBarTitleTextCentered: true,
                topBarElevationShadowEnabled:false
            },
			// backButtonHidden: true,
			navigatorButtons: {
                leftButtons:[
                    {
                        id: 'back',
                        icon: require("../../../img/hk_back_icon.png")
                    }
                ],
				rightButtons: [
					{
						id: 'reload',
                        testID: 'order_reload',
						title: '刷新'
					}
				]
			}
		});
	}

  _addOrder() {
      let {session} = this.props;
      let title = session && session.user && session.user.productKey == "HuLiZhan" ? "新增护理服务":"新增任务"

		  this.props.navigator.push({
          title: title,
			    screen: 'housekeeperapp.addorder',
          backButtonTitle:'',
			    passProps: {
				      source: 'create'
			    },
          navigatorStyle:{
              tabBarHidden: true,
              navBarTextColor: 'white',
            	navBarButtonColor: 'white',
            	navBarBackgroundColor: '#EA5404',
              statusBarColor: '#EA5404',
              navBarTitleTextCentered: true,
              topBarElevationShadowEnabled:false
          },
          navigatorButtons: {
              leftButtons:[
                  {
                      id: 'back',
                      icon: require("../../../img/hk_back_icon.png")
                  }
              ],
				      rightButtons: [
					        {
						          id: 'clear',
                      testID: 'order_clear',
						          title: '清空'
					        }
				      ]
			    }
		  });
	}

    _onRefresh() {
        this._retrieveOrderList();
	}

    _onLoadMore(){
        this._retrieveNextPage(this.props.status);
    }

    _renderBtn(){
        return (
            <View style={[styles.footerContainer,{marginLeft:15}]}>
                <Touch onPress={this._addOrder.bind(this)}>
                    <View style={styles.addOrder}>
                        <Image style={styles.addOrderImage} source={require('../../../img/hk_add_icon.png')} />
                        <Text style={styles.addOrderBtnText}>
                            新增任务
                        </Text>
                    </View>
                </Touch>
            </View>
        );
    }

    _renderRow(rowData, sectionID, rowID){
//<<<<<<< HEAD
        let user_role = this.props.session.user.role;

        if(rowData.isnodate){
            return this._renderNodata();
        }
//=======

      // if (rowData.isnodate) {
      //   return this._renderNodata()
      // }
//>>>>>>> master-temp

        if((this.list.length-1) == rowID){
             return (
                 <View key={rowID}>
                     <OrderCard 
                        info={rowData} 
                        topParent={this.props.parent} 
                        parent={this} 
                        viewOrder={this._viewOrder} 
                        navigator={this.props.navigator} 
                        />
                     {user_role==1?(this.props.status!=0?null:this._renderBtn()):null}
                 </View>
             )
        }else{
            return (
                <OrderCard 
                  key={rowID} 
                  info={rowData} 
                  topParent={this.props.parent} 
                  parent={this} 
                  viewOrder={this._viewOrder} 
                  navigator={this.props.navigator}
                  />
            )
        }
    }

    _renderNodata(){
        let user_role = this.props.session.user.role;
        return (
            <View style={this.props.status != 0?styles.noDataContent:styles.noDataContentWithBtn}>
                <Image source={require('../../../img/hk_no_data.png')} style={styles.leftImage}/>
                <Text style={{fontSize: 13, color: '#B5B5B5',marginTop:10}}>抱歉，暂无订单</Text>
                {user_role==1?(this.props.status != 0?null:this._renderBtn()):null}
            </View>
        );
    }

//<<<<<<< HEAD
    _onChangeTab({ i, ref }) {
        let {searchTab} = this.state;
        let {parent, tab} = this.props;

        if(searchTab === i){
            return;
        }

        this.overThreeTimeStyle = null;
        this.curTab = i;

		this.setState({ searchTab: i, overThreeTimeStyle: null });

        this.onLoad(null, parent.searchStrArr[tab]);
	}

    _leftSearch(){
        let style = {color: '#EA5404'};
        let {parent, tab} = this.props;
        let {allStyle} = this.state;

        if(allStyle){
            return;
        }

        this.overThreeTimeStyle = null;

        this.setState({
            allStyle:style,
            overThreeTimeStyle: null
        });

        this.onLoad(null, parent.searchStrArr[tab]);
    }

    _rightSearch(){
        let style = {color: '#EA5404'};
        let {overThreeTimeStyle} = this.state;
        let {parent, tab} = this.props;

        if(overThreeTimeStyle){
            return;
        }

        this.overThreeTimeStyle = style;
        this.curTab = 999;

        this.setState({
            overThreeTimeStyle:style,
            allStyle: null,
            searchTab: 999
        });

        this.onLoad(null, parent.searchStrArr[tab]);

    }

    _reloadData(){
        // let {parent, tab} = this.props;
        this.onLoad();
    }



    _loading(isShow){
      if (isShow) {
        this.loadingCont.setState({ "isShow": true, "text": '加载中...' });
      }else{
        this.loadingCont.setState({ "isShow": false});
      }
      
    }

    _renderTab(name, page, isTabActive, onPressHandler, onLayoutHandler){
        let {searchTab} = this.state;
        let textColor = isTabActive ? "#EA5404" : "#555555";
        if(searchTab == 999){
            textColor = "#555555";
        }


        return <Button
            key={`${name}_${page}`}
            accessible={true}
            accessibilityLabel={name}
            accessibilityTraits='button'
            onPress={() => onPressHandler(page)}
            onLayout={onLayoutHandler}
          >
            <View style={styles.tabStyle}>
              <Text style={{color: textColor}}>
                {name}
              </Text>
//=======
    {/*render() {
        return (
            
            <View style={styles.container}>
                <CustomListView
                    style={{flex:1}}
                    contentStyle={{backgroundColor:"#f3f3f3",paddingRight: 13, paddingBottom:10}}
                    footerStyle={this.props.status!=0?{marginTop:10}:{}}
                    ref={(component) => this._orderList = component }
                    onRefresh={this._onRefresh}
                    onLoadMore={this._onLoadMore}
                    renderRow ={this._renderRow.bind(this)}
                />
                <ToastTip ref="toast" offsetY={160}/>
                <LoadingTip show={this.state.showLoading}/>
>>>>>>> master-temp*/}
            </View>
          </Button>;
    }

    renderView(){
        let {overThreeTimeStyle, allStyle} = this.state;
        if(!this.props.session.user){
            return null;
        }

        let user_role = this.props.session.user.role;
        if(user_role == 1){//消息中心
            // dataList={this.props.tab == 2 && this.curTab == 1?this.list:null}
            return (
                <View style={styles.container}>
                    <View style={styles.searchContainer}>
                        <Touch style={styles.searchLeft} activeOpacity={0.7} onPress={this._leftSearch.bind(this)}>
                            <Text style={[styles.searchLeftBtn,allStyle?allStyle:{}]}>{"全部"}</Text>
                        </Touch>
                        <Touch style={styles.searchRight} activeOpacity={0.7} onPress={this._rightSearch.bind(this)}>
                            <Text style={[styles.searchRightBtn,overThreeTimeStyle?overThreeTimeStyle:{}]}>{this.props.status!=0?"第三方服务":"转单超3分钟"}</Text>
                        </Touch>
                    </View>
                    <CustomListView
                        style={{flex:1}}
                        contentStyle={{backgroundColor:"#f3f3f3",paddingRight: 13, paddingBottom:10}}
                        footerStyle={this.props.status!=0?{marginTop:10}:{}}
                        ref={(component) => this._orderList = component }
                        onRefresh={this._onRefresh}
                        onLoadMore={this._onLoadMore}
                        renderRow ={this._renderRow.bind(this)}
                    />
                    <ToastTip ref="toast" offsetY={160}/>
                    <Loading ref="loading"/>
                </View>
            )
        }else if (user_role == 0 || user_role == 2){
            //dataList={this.list.length>0?this.list:null}
            return (
                <View style={styles.container}>
                    <CustomListView
                        contentStyle={[{backgroundColor:"#f3f3f3",paddingRight: 13},this.props.tab==0||this.props.tab==1?{paddingBottom:54}:{paddingBottom:10}]}
                        footerStyle={this.props.status!=0?{marginTop:10}:{}}
                        ref={(component) => this._orderList = component }
                        onRefresh={this._onRefresh}
                        onLoadMore={this._onLoadMore}
                        renderRow ={this._renderRow.bind(this)}
                    />
                    <ToastTip ref="toast" offsetY={160}/>
                    <Loading ref="loading"/>
                    {this.props.tab==0||this.props.tab==1?<View style={styles.bottomRefresh}>
                        <Touch style={styles.bottomRefreshTouch} activeOpacity={0.7} onPress={this._reloadData.bind(this)}>
                            <Image source={require('../../../img/reload_icon.png')}/>
                            <Text style={styles.bottomRefreshTouchText}>刷新列表</Text>
                        </Touch>
                    </View>:null}
                </View>
            )
        }
    }

    render() {
        return this.renderView();
    }
}

var connectHelper = require('../../services/connectHelper');
OrderList = connectHelper(state => state)(OrderList);

module.exports = OrderList;
